Previous Page TOC Next Page


Visual C++™ 4 Unleashed

Viktor Toth

201 West 103rd Street, Indianapolis, Indiana 46290

Copyright © 1996 by Sams Publishing

FIRST EDITION

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams Publishing, 201 W. 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 0-672-30874-6

Library of Congress Catalog Card Number: 95-72334

99——98——97——96————————4——3——2——1

Interpretation of the printing code: the rightmost double-digit number is the year of the book's printing; the rightmost single-digit, the number of the book's printing. For example, a printing code of 96-1 shows that the first printing of the book occurred in 1996.

Printed in the United States of America

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Visual C++ is a trademark of Microsoft Corporation.

Publisher and President:

Richard K. Swadley

Acquisitions Manager:

Greg Wiegand

Development Manager:

Dean Miller

Managing Editor:

Cindy Morrow

Marketing Manager:

Gregg Bushyeager

Acquisitions Editor

Grace Buechlein

Development Editor

Anthony Amico

Software Development Specialist

Cari Skaggs

Production Editor

Carolyn Linn

Technical Reviewer

Daniel Boyle

Editorial Coordinator

Bill Whitmer

Technical Edit Coordinator

Lynette Quinn

Formatter

Frank Sinclair

Editorial Assistants

Sharon Cox

Andi Richter

Rhonda Tinch-Mize

Cover Designer

Jason Grisham

Book Designer

Alyssa Yesh

Production Team Supervisor

Brad Chinn

Overview

Preface

Introduction

Part I

The Visual C++ Development System

1

Visual C++ and the Developer Studio

2

Project Creation and the AppWizard

3

The ClassWizard and the WizardBar

4

Source Browsing

5

Debugging and Profiling

6

Code Reuse with the Component Gallery

Part II

The Windows Architecture and the Win32 API

7

Operating System Overview

8

The Message Loop

9

Windows, Dialog Boxes, and Controls

10

Resource Files

11

Drawing and Device Contexts

12

Threads and Processes

13

Memory Management

14

File Management

15

The Windows Clipboard

16

The Registry

17

Exception Handling

Part III

Microsoft Foundation Classes

18

Microsoft Foundation Classes: An Overview

19

Exploring an MFC Skeleton Application

20

Working with Documents and Views

21

Dialogs and Property Sheets

22

MFC Support for Common Dialogs and Common Controls

23

Using OLE Controls

24

Device Context and GDI Objects

25

Serialization: File and Archive Objects

26

Collection Classes

27

Exceptions, Multithreading, and Other MFC Classes

Part IV

OLE in MFC Applications

28

Object Linking and Embedding: An Overview

29

OLE Servers

30

OLE Containers

31

OLE Drag and Drop

32

OLE Automation

Part V

Advanced Programming Topics

33

Database Programming Through ODBC

34

Data Access Objects

35

Writing Messaging Applications with MAPI

36

OLE Control Development

37

Multimedia Applications

38

Implementing Context-Sensitive Help

39

TCP/IP Programming with WinsSock

40

Building Custom AppWizards

41

The OpenGL Graphics Library

42

Telephony Applications with TAPI

43

Network Programming with Pipes and Remote Procedure Calls

44

High-Performance Graphics and Sound: The Game SDK

Bibliography


Index



Preface

Writing about programming used to be very different from what it is today. In 1986, shortly before I left my native Hungary, I completed a book about the Commodore 16 home computer for a Hungarian publisher. In fewer than 400 pages, I provided a complete reference for that machine, down to the last tiny bit in the computer's ROM, the last transistor in its circuit diagram.

Assuming that it were possible to develop such a comprehensive reference for today's Windows 95-equipped desktop computers, that work would fill not only volumes, not only several bookshelves, but probably several large bookcases. The subject of "system calls" used to be a topic for a brief appendix in a typical programming book from the early 80s. Although these books are not yet old enough to have their pages turn yellow with age, the words in them seem to come from prehistoric times; today's programmer has to know more APIs than the number of system calls listed in many of these works!

Visual C++ is the fundamental programming tool for Windows. Writing about this programming environment requires covering most Windows programming topics in reasonable detail. One of the basic decisions an author has to make before embarking on such a task is to define the target audience.

This book is not for the novice programmer. Knowledge of the C and C++ programming languages, as well as a basic understanding of Windows programming fundamentals, is assumed.

This book is not a replacement for the excellent tutorial manuals that you find on your Visual C++ CD-ROM. What this book provides is a detailed introduction into many specific programming topics. Such introductions are often hard to find; function references and MFC class descriptions are a poor substitute for simple examples and helpful tips.

When I first started working with Visual C++ 1, I was thoroughly impressed by the power of the development environment. It took only a few short days with the Scribble tutorial application to get up to speed with MFC programming; afterwards, within less than a week, I was able to put together a Windows-based action game complete with multimedia sound effects.

With this experience behind me, it was not easy to understand why so many programmers, including people with years of C and C++ programming experience, had difficulty with Visual C++. Eventually, I think I understood the root of the problem. Many of these programmers have not had any prior exposure to Windows programming. The MFC Library does a wonderful job hiding many of the complex details of the Windows API; unfortunately, this also means that without prior exposure, you never have a chance to learn some fundamental concepts.

Let me show you an example. If you ever wrote a non-MFC Windows application, you must be familiar with the concept of the message loop. Essentially, all Windows applications have a WinMain function that looks something like this:

int WinMain(...)

{

    // Initialize main window

    ...

    while (!GetMessage(&msg, NULL, 0, 0))

        DispatchMessage(&msg)

    return msg.wParam;

}

The while loop in this function is the application's main message loop. All messages posted to the application are processed here and dispatched to the appropriate message handler functions.

As a programmer with Windows experience, you must also be familiar with the msg structure and what Windows messages generally look like. So if I tell you that the MFC Library provides its own version of WinMain, and that after initialization, it calls your CWinApp-derived object's Run member function that implements the message loop, you should have no problem understanding how MFC applications process Windows messages.

However, if you never wrote a non-MFC Windows application before, you might as well think that I wrote the above paragraphs in my native Hungarian. Message loop? Message structure? Message handlers? Dispatching? What do all these concepts mean?

This was my reasoning when I decided to devote a sizable portion of my book to Win32 programming topics. These topics form the very foundation upon which Visual C++ is built; without a thorough understanding of Win32 fundamentals, Visual C++ programming becomes a nightmare.

Not that this part is meant exclusively for those with little prior Windows programming exposure. Hopefully, even seasoned Windows programmers among you will find some of these chapters useful when you wish to understand more about such Win32 topics as structured exceptions, virtual memory, or programming with the Registry.

These topics do not require the Microsoft Foundation Classes; therefore, I liberally used simple, pedestrian examples that can be easily edited, compiled, and run from the command line. This simplicity is characteristic of all the examples I used in this book. My goal was not to demonstrate how good a programmer I am by adding all kinds of bells and whistles to these programs, but to illustrate specific programming concepts.

Take, for example, MAPI. If you have not done any MAPI programming before and wish to add some messaging features to your application, what would you prefer as your first exposure to MAPI? A comprehensive MFC-based example with a hundred kilobytes of source code? Here is what I offer instead:

#include <windows.h>

#include <stdio.h>

#include <mapi.h>

LPMAPILOGON lpfnMAPILogon;

LPMAPISENDMAIL lpfnMAPISendMail;

LPMAPILOGOFF lpfnMAPILogoff;

MapiRecipDesc recipient =

{

    0, MAPI_TO,

    "Bill Clinton", "SMTP:president@whitehouse.gov",

    0, NULL

};

MapiMessage message =

{

    0, "Greetings",

    "Hello, Mr. President!\n",

    NULL, NULL, NULL, 0, NULL, 1, &recipient, 0, NULL

};

void main(void)

{

    LHANDLE lhSession;

    HANDLE hMAPILib;

    hMAPILib = LoadLibrary("MAPI32.DLL");

    lpfnMAPILogon =

        (LPMAPILOGON)GetProcAddress(hMAPILib, "MAPILogon");

    lpfnMAPISendMail =

        (LPMAPISENDMAIL)GetProcAddress(hMAPILib, "MAPISendMail");

    lpfnMAPILogoff =

        (LPMAPILOGOFF)GetProcAddress(hMAPILib, "MAPILogoff");

    (*lpfnMAPILogon)(0, NULL, NULL, MAPI_ALLOW_OTHERS, 0,

                     &lhSession);

    (*lpfnMAPISendMail)(lhSession, 0, &message, 0, 0);

    (*lpfnMAPILogoff)(lhSession, 0, 0, 0);

    printf("Message to the White House sent.\n");

    FreeLibrary(hMAPILib);

}

This program, in all its 42 lines, is a fully functional command line-based MAPI application. It demonstrates how to load the MAPI library, use MAPI data structures, and call MAPI functions. Nor does compiling this program require a 1000-line make file (I always considered such huge make files somewhat obscene in examples); you can compile it from the command line by simply typing cl cmdmsg.c.

I actually use simple examples like this one regularly when I try to understand a new programming topic. Even when I find a suitable sample application somewhere, I often mutilate it by removing all nonessential fluff. After all, when I wish to learn about MAPI, I am not really interested in menus, resource files, or how to construct fancy dialogs.

This simplicity is perhaps most evident with my favorite Windows program, the Windows equivalent of the infamous Hello, World! program with which Kernighan and Ritchie introduce their bible on C programming. It has often been said that Windows programming is so complex, even the simplest of applications requires hundreds of lines of code. If you ever hear this again from diehard DOS or UNIX programmers, just show them the following program:

#include <windows.h>

int WINAPI WinMain(HINSTANCE d1, HINSTANCE d2, LPSTR d3, int d4)

{

    MessageBox(NULL, "Hello, World!", "", MB_OK);

}

Although the lines themselves are longer, this program has the exact same number of lines as the command line original:

#include <stdio.h>

void main(void)

{

    printf("Hello, World!\n");

}

As this example so well demonstrates, Windows programming can be made simple.

You will also notice that very few of the programming examples in this book are code fragments. I always found that a program that you can actually compile and run, no matter how simple it is, helps further your understanding of a subject a great deal more than code fragments. Such executable programs are also proof that the author actually tested the concepts presented; indeed, on the attached CD-ROM, you will find a ready-to-run executable for every example in this book. (I hope they will run on your machine; they run on mine.)

Let me say a few words about the topics and organization of this book. Part I is about the Developer Studio, which is the name for the new Visual C++ IDE (Integrated Development Environment). Some of its features are familiar to Visual C++ programmers, while other features, such as the Component Gallery or the WizardBar, are brand new. In this part, I also cover the two most important components of the Developer Studio, the AppWizard and the ClassWizard; additional topics include browsing and debugging applications, and using the Developer Studio in conjunction with other Microsoft development tools.

Part II is about programming in Windows with specific emphasis on 32-bit Windows programming. Many of the basic concepts of Windows programming are covered, and so are advanced 32-bit concepts such as thread management, virtual memory, structured exceptions, and the Registry.

Part III introduces the Microsoft Foundation Classes Library. Documents and views, dialogs, controls (including the use of OCXs), device contexts and GDI objects, serialization, collections, and miscellaneous classes are the topics of the 10 chapters that comprise this part.

Part IV is about OLE. In accordance with my philosophy of providing the fundamentals before presenting cookbook-like MFC recipes, I begin this part with a review of OLE fundamentals. A non-MFC example of a mere 300-some lines that is nevertheless a fully functional OLE automation server highlights some of the basic ideas presented in the first chapter. In the remaining four chapters, the use of MFC is explored in developing OLE containers, OLE component servers, OLE drag and drop applications, and OLE automation servers.

Part V contains an assortment of chapters about a variety of Visual C++ programming topics. ODBC, MAPI, TAPI, DAO, or OpenGL are just some of the acronyms that make up the subject of the chapters here.

At the beginning of this preface I mentioned how different programming books are today from those written a mere decade ago. Another difference is the rapidly changing nature of development environments. When I began my programming career, I used books on the FORTRAN language that were written 10 years earlier and were still perfectly useful; can you imagine trying to write a Windows 95 program using an MS-DOS programmer reference published in 1985?

Not only does this rapidly changing environment make the lives of programmers more difficult, it also takes its toll on authors. We can no longer afford the luxury of working on a book for a year or more; such a book would be rendered obsolete by new software versions even before it was published. I can only hope that despite the short time I had for developing this book, it does not contain too many glaring errors or omissions, and that it becomes a useful addition to your library.

Finally, I would like to thank my wife, Ildiko, for her unwavering support. Without her patience and understanding, the grueling routine of 14-hour work days and 7-day workweeks during the last two months would not have been possible.


About the Author

Viktor Toth is a Hungarian-born author and self-employed software developer. His professional career started in 1979, when he wrote his first Hungarian-language book on Ern› Rubik's Magic Cube. Between that time and 1986, he developed many scientific and business applications for clients in Hungary, Austria, Germany, and the United Kingdom. He wrote applications in Fortran, a variety of assemblers, Simula-67, C, and Pascal, just to name a few languages. In 1986, he authored his second book, a technical reference for programmers of the Commodore 16 home computer.

Viktor Toth became a resident of Canada in 1987. There, he continued his self-employed career. He coauthored several studies as a consultant for the Canadian government and wrote numerous applications in C and C++, assembler, dBase, and other environments. After briefly experimenting with other graphical systems such as the long-forgotten GEM, he eventually wrote his first Windows application in 1990 and has not looked back since.

Viktor Toth is coauthor of Sams Publishing's Windows 95 Programming Unleashed.

Viktor lives with his wife in their ever-smaller apartment in Ottawa, surrounded by several hundred pounds of computing equipment (his), knitting yarn (hers), and books. They hope to move soon to a house where they can add some cats to the family inventory.


What Is New in Visual C++ Version 4?

Whether Visual C++ 4 is revolutionary or merely evolutionary is subject to debate; but it certainly represents a major improvement over previous versions. If you liked the earlier versions, you must love Version 4; if you did not use Visual C++ before, it has never been easier to begin.

The improvements over earlier versions are in several areas. The new Integrated Development Environment (IDE) application, the Developer Studio, has a variety of new features. Among these are the improved ClassWizard, AppWizard, and an entirely new tool, the Component Gallery. The Microsoft Foundation Classes Library also has a new version that improves on earlier versions in many ways; it also adds support for the new Data Access Objects (DAO), another new redistributable component that ships with Visual C++. The C/C++ compiler component of Visual C++ also underwent some major revisions; in particular, the compiler supports several new elements of the emerging ANSI C++ standard, such as namespaces, run-time type information, and the Standard Template Library.


What Is New in the Developer Studio?

The new Developer Studio offers a variety of new and improved features for managing projects and subprojects, editing code and resources, managing classes, and for code reuse and code generation.

The Project Workspace

The Project Workspace window offers three views on projects: in Class View, project classes, member variables, and functions are shown; in File View files comprising a project are visible; and in Resource View, resource file components can be manipulated.

A workspace can now contain several projects. These can be top-level projects or subprojects.

Improved Editor

The new source code editor offers improved compatibility with Brief and other popular editors.

The ClassWizard and the WizardBar

The new ClassWizard offers support for OLE control development. Many ClassWizard features can easily be accessed in the WizardBar, a toolbar that is displayed in source editor windows.

Component Gallery

The Component Gallery is a major new component in Visual C++. Classes that are created through ClassWizard or entire projects created through AppWizard can be added to the Component Gallery and later inserted from here into other applications. The Component Gallery comes with many useful tools, including OLE controls and other components that add various useful features to your project.

Custom AppWizards

The new Visual C++ offers the capability to create custom AppWizards. Custom AppWizards can be based on existing AppWizard code or can be entirely custom made. Appropriately, creation of custom AppWizards is made easy by a custom AppWizard specifically written for this purpose.

Resource Editing

An improved Resource Editor now adds toolbars to the set of resource file components it can handle. Toolbar buttons can now be easily added, removed, or manipulated without having to modify corresponding structures or arrays in your code.

The dialog editing capabilities have also been improved; more accurate placement of dialog controls is now possible with the help of guides and margins. The Resource Editor can now also import Visual Basic forms.

Debugging

The integrated debugger has redesigned windows. It also offers a new feature, DataTips; positioning the mouse cursor over a symbol in an editor window during debugging causes a tooltip-style window to appear, displaying the current value of the symbol.

Integration with Other Tools

The Developer Studio offers a high level of integration with other Microsoft development tools such as the Microsoft Developer Library, Microsoft FORTRAN, Microsoft Test, and Microsoft SourceSafe.

Source Control

Visual C++ cooperates with source-code control systems that conform to the Microsoft Common Source Code Control Interface, such as Microsoft's own Visual SourceSafe.

The InfoViewer

The InfoViewer is a new, integrated tool for browsing online documentation. In addition to browsing the documentation that comes with Visual C++, it can also browse other titles, such as the Developer Network Library. It also has improved features, such as keyword browsing—the ability to search for highlighted words when the F1 key is pressed. (This feature was previously available only in source code windows.)

What Is New in the MFC Library?

The new MFC Library, MFC Version 4, offers several new classes and improved support in a number of areas.

Data Access Objects

The new MFC Library contains a series of new classes that encapsulate Data Access Objects (DAO). DAO is the technology used in Visual Basic, Microsoft Access, and other products to access databases through the Microsoft Jet engine.

OLE Controls

Support for the development of OLE controls, previously available in the form of a separate development tool (the Control Development Kit, or CDK), has now been fully integrated. The MFC supports OLE controls through a series of new classes. It also provides control container functionality through new member functions added to the CWnd class.

Synchronization Classes

The new MFC Library provides wrapper classes for a variety of synchronization objects, including events, mutexes, semaphores, and critical sections.

Windows 95 Common Controls

MFC support, previously available in add-on classes that were released in beta form as part of the Visual C++ subscription product, is now officially part of the MFC Library. In addition to classes that wrap control functionality, a series of new view and other classes have also been defined that support views based on list, tree, and rich-text edit controls.

What is New in the C/C++ Compiler?

The C/C++ compiler component of Visual C++ has been improved to provide better support for new features in the ANSI draft standard.

Namespaces

The compiler now supports namespaces. In addition to the single global namespace provided by the language, applications can define additional namespaces that provide unique scopes for globally defined objects. A namespace can be defined using the namespace keyword:

namespace A

{

int n;

}

Namespaces can be used explicitly or implicitly. Explicit use involves a syntax that is similar to the syntax used when referring to class members: for example, A::n. Implicit use requires the using keyword:

using namespace A;

printf("%d", n);

Run-Time Type Information

The new compiler supports ANSI-style Run-Time Type Information, or RTTI. RTTI is enabled through the /GR compiler command line option. RTTI introduces several new language elements. The typeid operator can be used to identify the type of an object. This operator returns an object of type type_info. For example:

class A { ... };

class B : public A { ... };

...

A *pa = new A;

B *pb = new B;

const type_info& ta = typeid(*pa);

const type_info& tb = typeid(*pb);

A series of new casting operators provides a replacement for old-style C casts while removing ambiguities. These operators include dynamic_cast, static_cast, const_cast, and reinterpret_cast.

The Standard Template Library

Visual C++ now provides support for the Hewlett-Packard public domain implementation of the Standard Template Library. Note that the STL is not installed by the Visual C++ setup program. Simultaneous use of STL and the MFC in the same application requires the use of namespaces due to conflicting declarations in the two libraries. ANSI recommends the use of the namespace std as the standard library namespace.

Run-Time Library Source

The source of the debug version of the C/C++ run-time library is now available. Using this source, it is now possible to step into run-time library functions during debugging.

Performance Improvements

The new compiler offers several performance improvements. The minimal rebuild option selects only those files for rebuild that are actually affected by changes in header files (as opposed to rebuilding all dependent source files). The incremental linker has been improved to handle more cases incrementally. The compiler's new incremental compilation feature detects portions of a source file that actually changed and limits compilation to these elements, greatly reducing compilation time.

Notational Conventions Used in This Book

Throughout Visual C++ 4 Unleashed, a simple notational style is used. All listings are typeset in a monospace font for ease of reading. In the text, the same monospace font is used for all function names, variable names, filenames, keywords, and other symbols that occur in programs. A monospace italic font is used for placeholders, such as function or method parameters, indicating that a symbol must be substituted in their place by the user. In some listings, a vertical line is used to mark code that must be added manually, to distinguish from code that was automatically generated or code that was added earlier. Throughout the book, many new terms are introduced; the first occurrence of such terms is highlighted by the use of an italic font.

Previous Page TOC Next Page